package com.flyxteam.commons.httpclient;

import java.security.NoSuchAlgorithmException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.net.ssl.SSLContext;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.stereotype.Component;

@Component

/**
 * @Description 连接池管理类，支持https协议
 * @author BZX
 */
public class HttpConnectionManager {
	
	/** 最大连接数 */
	private final static Integer HTTP_MAX_TOTAL = 200;
	
	/** 每个路由默认连接数 */
	private final static Integer HTTP_DEFAULT_MAX_PER_ROUTE = 20;
	
    static PoolingHttpClientConnectionManager cm = null;
    
    @PostConstruct
    public void init() {
        LayeredConnectionSocketFactory sslsf = null;
        try {
            sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory())
                .build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setMaxTotal(HTTP_MAX_TOTAL);
        cm.setDefaultMaxPerRoute(HTTP_DEFAULT_MAX_PER_ROUTE);
        
//        TODO 暂不开启  
//        new IdleConnectionMonitor.IdleConnectionMonitorThread(cm).start(); // 启动线程，5秒钟清空一次失效连接  
        
    }
    
    @PreDestroy
    public void close() {
    		cm.close();
    }
    
    /**
     * @Description 从连接池获取HttpClient
     * @return CloseableHttpClient
     */
    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .build();          
        
        /*CloseableHttpClient httpClient = HttpClients.createDefault();//如果不采用连接池就是这种方式获取连接*/
        return httpClient;
    }
}
